import axios from "axios";
import { useRouter } from "vue-router";
function getQueryString(name: string): number {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const r = window.location.search.substr(1).match(reg);
  if (r != null) return Number(unescape(r[2]));
  return 0;
}
// let baseURL = "http://123.56.85.24:5000/api/";
// 后台:http://app.changgongwang.com/sqKvcDVZWn.php/index/login?url=%2FsqKvcDVZWn.php%2Ftotal%2Fbill%3Fref%3Daddtabs
// let baseURL = "http://app.changgongwang.com/api/";
// let baseURL = "https://www.haiqiannengyuan.com/api/";
let baseURL = "https://app.changgongwang.com/api/"
// if (getQueryString("ip") == 1) {
//   baseURL = "http://123.56.85.24:5000/api/";
// } else if (getQueryString("ip") == 2) {
//   baseURL = "http://fq.lycent.cn/api";
// } else {
//   baseURL = "http://123.56.85.24:5000/api";
// }

// 创建FormData对象
let formData = new FormData();
const router = useRouter();
const service = axios.create({
  baseURL,
  timeout: 5000, // request timeout
  // 配置默认的Content-Type为multipart/form-data
  headers: {
    'Content-Type': 'multipart/form-data'
  }
});
// 发起请求之前的拦截器
service.interceptors.request.use(
  config => {
    // 设置Content-Type为application/x-www-form-urlencoded

    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    // 根据请求的URL判断是否需要设置Content-Type
    // if (config.url === "/sms/send") {
    //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    // } else if (config.url === "/user/mobilelogin"){
    //   config.headers['Content-Type'] = 'multipart/form-data';
    // }
    // 如果有token 就携带tokon
    const token = window.localStorage.getItem("accessToken");
    if (token) {
      // config.headers.common.Authorization = token;

      if (config.data instanceof FormData) {
        // 如果config.data是FormData对象，直接添加token
        config.data.append('token', token);
      }

      // // 如果config.data存在，并且是对象，添加到FormData中
      // if (config.data && typeof config.data === 'object') {
      //   Object.keys(config.data).forEach(key => {
      //     formData.append(key, config.data[key]);
      //   });
      // }

      // // 添加token到FormData
      // formData.append('token', token);
      // console.log(formData);
      // config.data = formData;
      // 将FormData对象赋值给config.data
      // config.data.push(formData);
    } else {
      // router.push({
      //   path:'/login'
      // })
    }
    return config;
  },
  error => Promise.reject(error)
);
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;

    if (response.status !== 200) {
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    return Promise.reject(error);
  }
);
export default service;
